#!/usr/bin/env bash
set -x

build_release_product() {
    set -xeuo pipefail;

    echo "RUNNING build_release_product"

    mkdir -p /tmp/env_yaml /tmp/conda-build /tmp/out

    local conda_build_args=();
    # The channel sequence below needs to be preserved
    conda_build_args+=(-c https://conda.anaconda.org/${CONDA_CHANNEL}/label/${CONDA_LABEL});
    conda_build_args+=(-c conda-forge);
    conda_build_args+=(--override-channels);
    conda_build_args+=(--croot /tmp/conda-build/cupynumeric);
    conda_build_args+=(--no-test);
    conda_build_args+=(--no-verify);
    conda_build_args+=(--no-build-id);
    conda_build_args+=("--build-id-pat=''");
    conda_build_args+=(--no-include-recipe);
    conda_build_args+=(--no-anaconda-upload);

    GPU_ENABLED=true
    [ "${USE_CUDA:-}" = "OFF" ] && GPU_ENABLED=false

    variantOpts=$(printf "{\"gpu_enabled\": [$GPU_ENABLED], \"build_tests\": [$BUILD_TESTS], \"python\": [$PYTHON_VERSION]}")

    conda_build_args+=(--variants "$variantOpts")

    # https://github.com/nv-legate/cupynumeric.internal/pull/351#issuecomment-2286922486
    export CONDA_OVERRIDE_CUDA="${LEGATE_CUDA_VERSION}"

    # Use the new .conda format.
    conda config --set conda_build.pkg_format 2

    # Set up the SCCACHE environment variables
    export CI=true
    source "${REPO_DIR}/continuous_integration/scripts/tools/legate-configure-sccache"
    sccache --zero-stats

    set +u;

    # For whatever reason, the default buffering of conda/mamba is not sufficient, and
    # leads to garbled output in CI (mixing conda output and whatever build.sh prints). So
    # we need to force unbuffered output.
    stdbuf -o0 -e0 conda mambabuild "${conda_build_args[@]}" "${REPO_DIR}/conda/conda-build";

    sccache --show-adv-stats

    copy_release_artifacts
}

copy_release_artifacts() {
    set -xeuo pipefail;
    echo Copying release artifacts

    cp -r /tmp/out          "$ARTIFACTS_DIR"
    cp -r /tmp/conda-build  "$ARTIFACTS_DIR"
    ls -lahR $ARTIFACTS_DIR
}

build_project() {
    . setup-utils;

    : "${LEGATE_CUDA_VERSION:?LEGATE_CUDA_VERSION must be set by the workflow matrix}"

    init_build_env "$@";

    . conda-dnld-utils;
    setup_conda_channel;
    generate_legate_version

    case "$BUILD_TYPE" in
        ci) build_release_product;;
        nightly) build_release_product;;
        *) return 1;;
    esac
}

(build_project "$@");
